package com.v1.video.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.iss.view.common.ToastAlone;
import com.iss.view.pulltorefresh.PullToRefreshBase;
import com.iss.view.pulltorefresh.PullToRefreshBase.Mode;
import com.iss.view.pulltorefresh.PullToRefreshBase.OnRefreshListener2;
import com.iss.view.pulltorefresh.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.analytics.MobclickAgent;
import com.v1.video.AppContext;
import com.v1.video.Constant;
import com.v1.video.R;
import com.v1.video.adapter.ThemeMyThemeAdapter;
import com.v1.video.db.dao.MyThemeTB;
import com.v1.video.db.dao.MyThemeVideoTB;
import com.v1.video.db.dao.ThemeTB;
import com.v1.video.db.service.ThemeMyThemeDB;
import com.v1.video.domain.LoginInfo;
import com.v1.video.domain.SubscribeMyEntity;
import com.v1.video.domain.SubscribeMyObj;
import com.v1.video.domain.ThemeAllThemeEntity;
import com.v1.video.httpApi.V1VideoHttpApi;
import com.v1.video.httpmanager.RequestManager;
import com.v1.video.httpmanager.RequestManager.OnResponseListener;
import com.v1.video.pay.MD5;
import com.v1.video.util.Logger;
import com.v1.video.util.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * 主题：我的主题
 * 
 * @author fengtao
 * 
 */
public class FragmentThemeMyTheme extends V1BaseFragment implements IRefresh {
	private final String TAG = "FragmentThemeMyTheme";
	private LayoutInflater mInflater;
	private View mRootView;
	private PullToRefreshListView refreshListView = null;
	private ListView listview = null;
	private ThemeMyThemeAdapter adapter = null;
	private List<MyThemeTB> listVideo = new ArrayList<MyThemeTB>();
	private LinearLayout layoutHasData = null;
	private LinearLayout layoutNoDataToUpdata = null;
	private RelativeLayout layoutNoData = null;
	private RelativeLayout btnGotoSelection = null;

	private final int STATE_REFRESH = 0X0001;// 下拉刷新
	private final int STATE_GO_THEME_ALL = 0X0002;// 全部主题
	private Handler handlerTheme;
	private TextView txtToLoginOrSelection = null;
	boolean isAskingServer = false;
//	View viewEmpty = null;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mInflater = inflater;
		mRootView = mInflater.inflate(R.layout.fragment_theme_mytheme,
				container, false);
		initView();
		initData();
		setListener();
		//进入时，访问 服务器，主题日否删除，进入时更新全部主题，的关注状态；
		return mRootView;
	}

	public FragmentThemeMyTheme(Handler handlerTheme) {
		this.handlerTheme = handlerTheme;
	}

	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onPageStart("主题-我的主题");
		viewOfNoLogin();
	}
	
	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		if(!hidden){
			viewOfNoLogin();
		}
	}


	private void viewOfNoLogin() {
		refreshListView.setVisibility(View.VISIBLE);
		layoutNoData.setVisibility(View.GONE);
//		adapter = null;
		refreshPullDown(true);
		if(listVideo != null && listVideo.size() > 0){
			getTheThemeStateFromServer();
		}
	}
	
	private void getTheThemeStateFromServer(){
		String url = V1VideoHttpApi.GET_THEME_STATE();
		//http://static.app.m.v1.cn/www/mod/mob/ctl/theme/act/gettotallist/p/5/pcode/010110000/version/4.3.mindex.html
		Logger.i(TAG, "全部主题的url="+url);
		RequestManager.getInstance().postRequest(this.getActivity(), url, ThemeAllThemeEntity.class,"FragmentThemeMyTheme", new OnResponseListener(){

			@Override
			public void onSuccess(Object object, int code, String message,String key) {
				// TODO Auto-generated method stub
				Logger.i(TAG, "onSuccess.object="+object.toString());
				if(refreshListView != null){
					Logger.i(TAG, "refreshListView.onRefreshComplete()");
					refreshListView.onRefreshComplete();
				}
				isAskingServer = false;
				if(object != null){
					ThemeAllThemeEntity themeAllData = (ThemeAllThemeEntity)object;
					AppContext context = (AppContext) getActivity().getApplicationContext();					
					com.v1.video.domain.BaseEntity.Header header = themeAllData.getHeader();
					if(header.getStatus().equals("2")){						
						return;
					}
					
					//!isSame若不一样，则 替换存储，替换显示，提示有更新//获取数据后 ，若本地不存在，则直接存储，直接显示，
					if(themeAllData.getBody() != null){
						if(themeAllData.getBody().getData() != null && themeAllData.getBody().getData().size() > 0){
							
							if(listVideo != null){
								boolean isHasUnData = false; //是否含有已删除主题
								for(int i = 0; i < themeAllData.getBody().getData().size();i++){
									ThemeTB theme = themeAllData.getBody().getData().get(i);
									for(int j = 0; j<listVideo.size();j++){
										MyThemeTB themeMy = listVideo.get(j);
										if(theme.getThemeID().equals(themeMy.getThemeID())){
											if(theme.getStatus().equals("0")){
												isHasUnData = true;
												List<MyThemeVideoTB> list = listVideo.get(j).getVideoList();
												ThemeMyThemeDB.getInstance().deleteInTx(list);
												ThemeMyThemeDB.getInstance().deleteTheTheme(theme.getThemeID());
											}
											break;
										}
									}
								}
								if(isHasUnData){
									//重新刷新listVideo;
									refreshPullDown(true);
								}
							}
							if(adapter != null){
								adapter.updata(listVideo);
								adapter.notifyDataSetChanged();
							}
							Constant.isUploadOfSubscribeMy = true;
						}else{
						}
					}else{
						ToastAlone.showToast(getActivity(), "网络异常，请稍后再试~", 1);
					}
				}
			}

			@Override
			public void onFailure(int code, String message) {
				// TODO Auto-generated method stub
				Logger.i("tag---onFailure", message);
				isAskingServer = false;
				if(refreshListView != null){
					refreshListView.onRefreshComplete();
				}
			}
			
		});
	}

	@Override
	public void onPause() {
		super.onPause();
		// MobclickAgent.onPageEnd("订阅");
		MobclickAgent.onPageEnd("主题-我的主题");
	}

	public Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case STATE_REFRESH:
				Logger.i(TAG, "handleMessage执行了");
//				if (refreshListView != null) {
//					refreshListView.onRefreshComplete();
//				}

				break;
			}
		}

	};

	private void initView() {
		refreshListView = (PullToRefreshListView) mRootView
				.findViewById(R.id.fragment_subscribe_listview);
		listview = refreshListView.getRefreshableView();
		refreshListView.setMode(Mode.DISABLED);
		layoutHasData = (LinearLayout) mRootView
				.findViewById(R.id.fragment_subscribe_updata);
		layoutNoDataToUpdata = (LinearLayout) mRootView
				.findViewById(R.id.fragment_subscribe_noupdata);
		layoutNoData = (RelativeLayout) mRootView
				.findViewById(R.id.fragment_subscribe_my_nodata);
		btnGotoSelection = (RelativeLayout) mRootView
				.findViewById(R.id.fragment_subscribe_btn_back);
		txtToLoginOrSelection = (TextView) mRootView
				.findViewById(R.id.fragment_subscribe_my_nodata_txt);
//		viewEmpty = View.inflate(getActivity().getApplicationContext(),
//				R.layout.fragment_no_content, null);
	}

	private void initData() {
		// refreshPullDown(false);
		
	}

	/** 加载数据 */
	private void refreshPullDown(Boolean isUpdata) {
		if (ThemeMyThemeDB.getInstance().getAllMyThemeData() != null
				&& ThemeMyThemeDB.getInstance().getAllMyThemeData().size() > 0) {
			layoutNoData.setVisibility(View.GONE);
			listview.setVisibility(View.VISIBLE);
			listVideo = ThemeMyThemeDB.getInstance().getAllMyThemeData();
			for(int i = 0; i < listVideo.size();i++){
				List<MyThemeVideoTB> listMythemeVideo = ThemeMyThemeDB.getInstance().getMyThemdVideoFromMyTheme(listVideo.get(i).getThemeID());
				listVideo.get(i).setVideoList(listMythemeVideo);
			}
			if (adapter != null) {
				adapter.updata(listVideo);
				adapter.notifyDataSetChanged();
			} else {
				adapter = new ThemeMyThemeAdapter(getActivity(), listVideo);
				listview.setAdapter(adapter);
			}
		} else {
			listview.setVisibility(View.GONE);
			layoutNoData.setVisibility(View.VISIBLE);
		}
//		String key = "FragmentThemeMyTheme";
//		key = MD5.getMessageDigest(key);
//		if (!Helper.checkConnection(getActivity())) {
//			AppContext context = (AppContext) getActivity()
//					.getApplicationContext();
//			// key =
//			// MD5.getMessageDigest(Constant.GET_SUBSCRIBE_MY_1+LoginInfo.getInstance().getUserId()+Constant.GET_SUBSCRIBE_MY_2);
//			if (context.getMemeryCache().isExist(key)) {
//				// 若有缓存，则读缓存，显示数据；缓存读取到listVideo
//				Logger.i(TAG, "有缓存111111111");
//				getDataFromCache(key);
//				if (adapter != null) {
//					adapter.updata(listVideo);
//					adapter.notifyDataSetChanged();
//				} else {
//					adapter = new ThemeMyThemeAdapter(getActivity(), listVideo);
//					listview.setAdapter(adapter);
//				}
//			} else {
//				Logger.i(TAG, "无缓存11111111");
//				View view = listview.getEmptyView();
//				if (view == null) {
//					listview.setEmptyView(viewEmpty);
//				}
//			}
//			// 若无缓存，则不显示数据；
//			if (refreshListView != null) {
//				refreshListView.onRefreshComplete();
//			}
//		} else {
//			if (isUpdata) {// 下拉刷新直接从服务器读取数据；
//				getDataFromServer();
//				return;
//			} else {
//				if (Constant.isUploadOfSubscribeMy) {
//					// 读缓存
//					Logger.i(TAG, "非第一次进，读缓存111111111");
//					getDataFromCache(key);
//					if (adapter != null) {
//						// adapter.updata(listVideo);
//						// adapter.notifyDataSetChanged();
//						listview.setAdapter(adapter);
//					} else {
//						adapter = new ThemeMyThemeAdapter(getActivity(),
//								listVideo);
//						listview.setAdapter(adapter);
//					}
//				} else {
//					Logger.i(TAG, "第一次进，读服务器111111111");
//					getDataFromServer();
//				}
//			}
//		}
	}

	private void getDataFromServer() {
		String url = Constant.GET_SUBSCRIBE_MY_1 + "/"
				+ LoginInfo.getInstance().getUserId()
				+ V1VideoHttpApi.GET_SUBSCRIBE_MY_2();
		// String url =
		// "http://192.168.9.105:81/www/mod/mob/ctl/subscription/act/my/uid/6224222/pcode/010110000/version/4.0.mindex.html";
		Logger.i("url", "我的订阅的url=" + url);
		RequestManager.getInstance().getRequest(this.getActivity(), url, null,
				SubscribeMyEntity.class, 0, "FragmentSubscribeSelection",
				new OnResponseListener() {

					@Override
					public void onSuccess(Object object, int code,
							String message, String key) {
						// TODO Auto-generated method stub
						Logger.i(TAG, "onSuccess.object=" + object.toString());
						if (refreshListView != null) {
							Logger.i(TAG, "refreshListView.onRefreshComplete()");
							refreshListView.onRefreshComplete();
						}
						isAskingServer = false;
						// key =
						// MD5.getMessageDigest(Constant.GET_SUBSCRIBE_MY_1+Constant.GET_SUBSCRIBE_MY_2);
						if (object != null) {
							boolean isSame = true;// 新数据和旧数据是否一样；
							SubscribeMyEntity subScribeMyData = (SubscribeMyEntity) object;
							AppContext context = (AppContext) getActivity()
									.getApplicationContext();
							com.v1.video.domain.BaseEntity.Header header = subScribeMyData
									.getHeader();
							if (header.getStatus().equals("2")) {
								layoutNoData.setVisibility(View.VISIBLE);
								txtToLoginOrSelection
										.setText(getResources()
												.getString(
														R.string.tips_title_subscribe_my_no_updata_tuijian));
								refreshListView.setVisibility(View.GONE);
								return;
							} else {
								layoutNoData.setVisibility(View.GONE);
								refreshListView.setVisibility(View.VISIBLE);
							}
							isSame = judgeOldAndrNewData(key, context, header);

							// !isSame若不一样，则 替换存储，替换显示，提示有更新//获取数据后
							// ，若本地不存在，则直接存储，直接显示，
							if (subScribeMyData.getBody() != null) {
								if (subScribeMyData.getBody().getData() != null
										&& subScribeMyData.getBody().getData()
												.size() > 0) {

									if (!isSame
											|| !context.getMemeryCache()
													.isExist(key)) {
										if (header != null
												&& header.getMarkid() != null) {
											context.getMemeryCache().putDB(key,
													header.getMarkid());
											saveInfoToFile(subScribeMyData
													.getBody().getData(), key);
										}
										// 提示有数据更新
										toastUpdata();
									}
									// if(adapter != null){
									// if(!isSame){
									// adapter.updata(subScribeMyData.getBody().getData());
									// adapter.notifyDataSetChanged();
									// }
									// }else{
									// adapter = new
									// ThemeMyThemeAdapter(getActivity(),
									// subScribeMyData.getBody().getData());
									// listview.setAdapter(adapter);
									// }
									Constant.isUploadOfSubscribeMy = true;
								} else {
									if (!context.getMemeryCache().isExist(key)) {
										View view = listview.getEmptyView();
										if (view == null) {
//											listview.setEmptyView(viewEmpty);
										}
									}
								}
							} else {
								ToastAlone.showToast(getActivity(),
										"网络异常，请稍后再试~", 1);
							}
						}
					}

					@Override
					public void onFailure(int code, String message) {
						// TODO Auto-generated method stub
						Logger.i("tag---onFailure", message);
						isAskingServer = false;
						if (refreshListView != null) {
							refreshListView.onRefreshComplete();
						}

						// 判断是否登录，若登录，判断是否有缓存，若有缓存，则显示数据，若无缓存则显示 empty
						// 若未登录，显示未登录的数据；
						if (!LoginInfo.getInstance().isLogin()) {
							layoutNoData.setVisibility(View.VISIBLE);
							refreshListView.setVisibility(View.GONE);
							txtToLoginOrSelection
									.setText(getResources()
											.getString(
													R.string.tips_title_subscribe_my_no_login));
						} else {
							String key = MD5
									.getMessageDigest(Constant.GET_SUBSCRIBE_MY_1
											+ LoginInfo.getInstance()
													.getUserId()
											+ V1VideoHttpApi.GET_SUBSCRIBE_MY_2());
							if (((AppContext) getActivity()
									.getApplicationContext()).getMemeryCache()
									.isExist(key)) {
								// 若有缓存，则读缓存，显示数据；缓存读取到listVideo
								Logger.i(TAG, "有缓存111111111");
								getDataFromCache(key);
								if (adapter != null) {
									adapter.updata(listVideo);
									adapter.notifyDataSetChanged();
								} else {
									adapter = new ThemeMyThemeAdapter(
											getActivity(), listVideo);
									listview.setAdapter(adapter);
								}
							} else {
								Logger.i(TAG, "无缓存11111111");
								View view = listview.getEmptyView();
								if (view == null) {
//									listview.setEmptyView(viewEmpty);
								}
							}
						}
					}

				});
	}

	/***
	 * //若本地存在缓存，则判断：若一样，则不做存储，提示 无更新
	 * 
	 * @param key
	 * @param context
	 * @param header
	 * @return
	 */
	private boolean judgeOldAndrNewData(String key, AppContext context,
			com.v1.video.domain.BaseEntity.Header header) {
		boolean isSame = true;
		if (context.getMemeryCache().isExist(key)) {
			Logger.i(TAG, "有缓存2222222222222");
			String value = context.getMemeryCache().get(key);

			if (header != null) {
				if (!value.equals("") && header.getMarkid() != null
						&& value.equals(header.getMarkid())) {
					// 两次数据一致，提示没有更新
					// toastNoUpdata();
					// if(adapter == null){
					// getDataFromCache();
					// adapter = new SubscribeSelectionAdapter(getActivity(),
					// listVideo);
					// listview.setAdapter(adapter);
					// }
					// return;
				} else {
					isSame = false;// 两次数据不一致，下面拿到数据去存储；
				}
			}
		} else {
			Logger.i(TAG, "无缓存2222222222222");
		}
		return isSame;
	}

	private void setListener() {
		refreshListView.setOnRefreshListener(new OnRefreshListener2() {

			@Override
			public void onPullDownToRefresh(PullToRefreshBase refreshView) {
				// TODO Auto-generated method stub
				Logger.d(TAG, "下拉刷新");

//				if (!LoginInfo.getInstance().isLogin()) {
//					layoutNoData.setVisibility(View.VISIBLE);
//					refreshListView.setVisibility(View.GONE);
//					txtToLoginOrSelection.setText(getResources().getString(
//							R.string.tips_title_subscribe_my_no_login));
//					return;
//				} else {
//					refreshListView.setVisibility(View.VISIBLE);
//					layoutNoData.setVisibility(View.GONE);
//					refreshPullDown(true);
//				}
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase refreshView) {
				// TODO Auto-generated method stub

			}

		});
		refreshListView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				switch (scrollState) {
				case OnScrollListener.SCROLL_STATE_IDLE:
					ImageLoader.getInstance().resume();
					break;
				case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
					ImageLoader.getInstance().pause();
					break;
				case OnScrollListener.SCROLL_STATE_FLING:
					ImageLoader.getInstance().pause();
					break;
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub

			}
		});
		btnGotoSelection.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Logger.i(TAG, "点击去精选了");
//				if (!LoginInfo.getInstance().isLogin()) {
//					Intent intent_login = new Intent(getActivity(),
//							SettingLoginActivity.class);
//					intent_login.putExtra("loginFlag", 3);
//					startActivityForResult(intent_login,
//							Constant.REQUESTCODE_LOGIN_CODE);
//				} else {
					Message msg = new Message();
					msg.what = STATE_GO_THEME_ALL;
					handlerTheme.sendMessage(msg);
//				}
			}
		});

//		viewEmpty.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				// TODO Auto-generated method stub
//				if (!Helper.checkConnection(getActivity())) {
//					return;
//				}
//				if (!isAskingServer) {
//					isAskingServer = true;
//					getDataFromServer();
//				}
//			}
//		});
	}

	private void getDataFromCache(String key) {
		if (listVideo != null) {
			listVideo.clear();
		}
		listVideo = null;// Utils.getSubscribeMyInfoFromFile(getActivity(),key);
		// if(listVideo == null){
		// listVideo = new ArrayList<MyThemeTB>();
		// }
	}

	private void saveInfoToFile(List<SubscribeMyObj> listVideo, String key) {
		Gson gson = new Gson();
		Utils.saveSubscribeMyToFile(getActivity(), gson.toJson(listVideo), key);
	}

	private void toastNoUpdata() {
		layoutNoDataToUpdata.setVisibility(View.VISIBLE);
		AlphaAnimation anim = new AlphaAnimation(1.0f, 0.01f);
		anim.setDuration(4000);
		anim.setAnimationListener(new Animation.AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
			}

			@Override
			public void onAnimationEnd(Animation animation) {
				// 渐变动画结束后，执行此方法，跳转到主界面
				layoutNoDataToUpdata.setVisibility(View.GONE);
			}
		});
		layoutNoDataToUpdata.setAnimation(anim);
		anim.start();
	}

	private void toastUpdata() {
		if (Constant.isUploadOfSubscribeMy) {
			layoutHasData.setVisibility(View.VISIBLE);
			AlphaAnimation anim = new AlphaAnimation(1.0f, 0.01f);
			anim.setDuration(4000);
			anim.setAnimationListener(new Animation.AnimationListener() {

				@Override
				public void onAnimationStart(Animation animation) {
				}

				@Override
				public void onAnimationRepeat(Animation animation) {
				}

				@Override
				public void onAnimationEnd(Animation animation) {
					// 渐变动画结束后，执行此方法，跳转到主界面
					layoutHasData.setVisibility(View.GONE);
				}
			});
			layoutHasData.setAnimation(anim);
			anim.start();
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		Logger.i(TAG, "onActivityResult执行了111111111111");
		if (LoginInfo.getInstance().isLogin()) {
			refreshListView.setVisibility(View.VISIBLE);
			layoutNoData.setVisibility(View.GONE);
			refreshPullDown(false);
		}
	}
}
